package com.zqg8512.netty.reponse;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;

import java.net.SocketAddress;

/**
 * @Author zengqianggang
 * @Description //TODO
 * Author VPN
 * @Date 2019/9/30 10:30
 * @Version 1.0
 **/
public class MyChannelParse extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        Channel channel = ctx.channel();

        SocketAddress socketAddress = channel.remoteAddress();

        System.out.println("地址："+ socketAddress);

        ReponseTO ok = ReponseTO.ok("你赢了", "不会给你任何东西");

        ByteBuf byteBuf = Unpooled.copiedBuffer(ok.toString(), CharsetUtil.UTF_8);

        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);

        // response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);
        // 上面的 中文会乱码
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=utf-8");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());

        // 没有用
        // response.headers().add(HttpHeaderNames.ACCEPT_CHARSET, "UTF-8");


        ctx.writeAndFlush(response);
    }
}
